package com.example.demo.Service.Impl;

import com.example.demo.Entity.Chunk;
import com.example.demo.Entity.ChunkInfo;
import com.example.demo.Entity.FSFile;
import com.example.demo.Entity.FSFolder;
import com.example.demo.Master.MasterBase;
import com.example.demo.Service.FileService;
import com.example.demo.Util.EncodeMD5;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.*;


@Service
public class FileServiceImpl implements FileService {


    //上传文件（虚拟）
    public String uploadFile(String userName, String filePath, String type,long size,MasterBase masterBase){

        FSFolder rootFolder = masterBase.getRoot();
        FSFolder childFolder;
        if(rootFolder.getChildFolderList() == null){
            LinkedList<FSFolder> folderTree = new LinkedList<>();
            rootFolder.setChildFolderList(folderTree);
        }
        childFolder = rootFolder.getFolderByName(rootFolder.getChildFolderList(),userName);
        if(childFolder == null){
            childFolder = rootFolder.createNewFolder(new StringBuffer(userName));
        }
        childFolder.addByPath(filePath,type,size);

        int len = Integer.MAX_VALUE;
        String serverName = null;
        for(String key : masterBase.getChunkServerMap().keySet()){
            int tem = masterBase.getChunkServerMap().get(key).getNum();
            if(len >= tem){
                len = tem;
                serverName = key;
            }
        }
        return serverName;
    }

    //上传文件（实际）
    public void uploadTrueFile(String serverName,String filePath,String content,String userName,MasterBase masterBase){
        //filePath包含文件名，例如/qqq/www/eee/r.txt
        String serverPath = new String("D:\\root\\"+serverName+"\\");
        int index = filePath.lastIndexOf("/");
        String tem = filePath.substring(index);
        String fileName = new String(tem+".chunk");
        File file = new File(serverPath+fileName);
        try {
            if(!file.exists()){
                file.createNewFile();
                FileWriter fileWritter = new FileWriter(file.getName());
                fileWritter.write(content);
                fileWritter.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //给hash值
        String hash = EncodeMD5.encodeMD5(file);
        File newFile = new File(serverPath+hash);
        file.renameTo(newFile);


        //id和长度待修改
        Chunk fileChunk = new Chunk(1,0);

        ChunkInfo fileChunkInfo = new ChunkInfo(fileChunk,hash);
        fileChunkInfo.setServerName(serverName);

        //备用服务器设置，待补充
        fileChunkInfo.setFirstCopyServerName("server4");
        fileChunkInfo.setSecondCopyServerName("server5");

        String path = new String("/root/"+userName+filePath);
        masterBase.getChunkInfoMap().put(path,fileChunkInfo);
    }

    //在线查看文件内容
    public String browseFiles(String userName,String filePath,MasterBase masterBase){
        String path = new String("/root/"+userName+filePath);
        ChunkInfo chunkInfo = masterBase.getChunkInfoMap().get(path);
        String serverName = chunkInfo.getServerName();
        int index = filePath.lastIndexOf("/");
        String tem = filePath.substring(index);
        String fileName = new String(tem+".chunk");
        String address = new String("D:\\root\\"+serverName+"\\"+fileName);
        StringBuffer contentBuffer = new StringBuffer();
        File file = new File(address);
        try{
            FileReader fr = new FileReader(file);
            char[] a = new char[(int)file.length()];
            fr.read(a);
            for (char c : a) {
                contentBuffer.append(c);
                fr.close();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        String content = new String(contentBuffer);
        return content;
    }

    //显示文件列表
    public List showList(String userName, String folderPath, MasterBase masterBase){
        List<FSFile> list = new LinkedList<>();
        FSFolder target = masterBase.getRoot().getFolderByName(masterBase.getRoot().getChildFolderList(),userName).getFSFolderByPath(folderPath);

        //扫描文件列表
        for(FSFile files : target.getFilelist()){
            FSFile temfile = new FSFile(files.getName().toString(),files.getTime().toString(),files.getSize(),files.isShare(),files.getType(),files.isRecycle());
            ((LinkedList<FSFile>) list).addLast(temfile);
        }

        //扫描文件夹列表（借用FSFile数据结构）
        for(FSFolder folders : target.getChildFolderList()){
            FSFile temfolder = new FSFile(folders.getName().toString(),folders.getTime().toString(),folders.getSize(),false,"folder",false);
            ((LinkedList<FSFile>) list).addLast(temfolder);
        }

        return list;
    }

    //删除文件到回收站
    public void deleteToRecycle(String userName,String filePath,MasterBase masterBase){
        String path = new String("/"+userName+filePath);
        masterBase.getRoot().getFSFileByPath(path).setRecycle(true);
    }

    //重命名文件
    public void renameFile(String userName,String filePath,MasterBase masterBase,String newName){
        String tempath = new String("/"+userName+filePath);
        masterBase.getRoot().getFSFileByPath(tempath).setName(new StringBuffer(newName));
        String path = new String("/root/"+userName+filePath);
        int index = path.lastIndexOf("/");
        String newPath = path.substring(0,index)+"/"+newName;
        masterBase.getChunkInfoMap().put(newPath,masterBase.getChunkInfoMap().remove(path));
    }
}
